import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from "@/user/LoginView";
import MainView from "@/user/MainView";
import WelcomeView from "@/user/WelcomeView";
import {Message} from "element-ui";
import RoleView from "@/user/RoleView";


Vue.use(VueRouter)

const routes = [
    {path: '/', name: 'LoginView', component: LoginView},
    {
        path: '/main',
        name: 'MainView',
        component: MainView,
        children: [
            {path: '/welcome', name: 'WelcomeView', component: WelcomeView},
            {path: '/role/select', name: 'RoleView', component: RoleView}
        ]
    },
]

const router = new VueRouter({
    routes
})
// 添加路守卫
router.beforeEach(async (to, from, next) => {
    // 按官网提供的示例，做修改
    let token = sessionStorage.getItem("token");
    console.log(token)
    console.log("上一个视图",  from )
    console.log("要访问的视图名：" + to.name)
    if (token == null && to.name != 'LoginView') {
        console.log("---- 前端守卫，拦截没有登录 ----")
        Message({
            type: "error",
            message: "对不起，请先登录",
            duration: 1000
        })
        // 将用户重定向到登录页面
        return {name: 'LoginView'}
    }
    next();
})

export default router
